package com.qdlc.p2p.biz.service.impl;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.qdlc.p2p.biz.executer.AbstractExecuter;
import com.qdlc.p2p.biz.executer.ExecuterHelper;
import com.qdlc.p2p.biz.executer.impl.ApplyUserCreditExecuter;
import com.qdlc.p2p.biz.executer.impl.VerifyApplyUserCreditExecuter;
import com.qdlc.p2p.biz.service.UserCreditService;
import com.qdlc.p2p.common.constant.Global;
import com.qdlc.p2p.dal.dao.UserCreditApplyDao;
import com.qdlc.p2p.dal.dao.UserCreditDao;
import com.qdlc.p2p.dal.dao.UserCreditLogDao;
import com.qdlc.p2p.dal.dao.VerifyLogDao;
import com.qdlc.p2p.dal.dto.*;

@Service("userCreditService")
public class UserCreditServiceImpl implements UserCreditService {

    @Resource
    private UserCreditDao userCreditDao;

    @Resource
    private UserCreditApplyDao userCreditApplyDao;

    @Resource
    private UserCreditLogDao userCreditLogDao;

    @Resource
    private VerifyLogDao verifyLogDao;

    public UserCredit findByUserId(long userId) {
        return userCreditDao.findObjByProperty("user.userId", userId);
    }

    @Override
    public void update(double totalVar, double useVar, double nouseVar, long userId) {
        userCreditDao.update(totalVar, useVar, nouseVar, userId);
    }

    /**
     * 申请信用额度
     */
    @Override
    public void applyUserCredit(UserCreditApply userCreditApply) {
        // 添加信用额度审核记录
        userCreditApplyDao.save(userCreditApply);
        // 进入executer处理
        Global.setTransfer("userCreditApply", userCreditApply);
        AbstractExecuter executer = ExecuterHelper.getExecuter(ApplyUserCreditExecuter.class);
        executer.execute(0, userCreditApply.getUser());
    }

    /**
     * 审核信用额度
     */
    @Override
    public void verifyApplyUserCredit(UserCreditApply userCreditApply, UserCreditLog userCreditLog, Operator operator) {
        // 更新信用额度申请信息
        userCreditApplyDao.save(userCreditApply);
        // 添加信用额度日志
        userCreditLogDao.save(userCreditLog);

        // 进入execute处理
        AbstractExecuter executer = ExecuterHelper.getExecuter(VerifyApplyUserCreditExecuter.class);
        Global.setTransfer("userCreditApply", userCreditApply);
        executer.execute(0, userCreditApply.getUser(), operator);

        // 添加审核日志
        VerifyLog verifyLog = new VerifyLog(new Operator(userCreditApply.getVerifyUser()), "credit",
                userCreditApply.getId(), 2, userCreditApply.getStatus(), userCreditApply.getRemark());
        verifyLogDao.save(verifyLog);
    }
}
